package cloud_live

import (
	"bytes"
	"encoding/json"
	"errors"
	"github.com/tidwall/gjson"
	"io/ioutil"
	"net/http"
	"net/url"
	"vrcm/src/vrcm/app/admin/models"
	dto "vrcm/src/vrcm/app/admin/service/dto/live"
	"vrcm/src/vrcm/common/service"
	ext "vrcm/src/vrcm/envconfig"
)

var client = http.Client{}

type CloudLive struct {
	service.Service
}

func (e *CloudLive) StartPullLive(d dto.StartPullLiveReq) (string, error) {
	params := url.Values{}
	urlString := ext.ExtConfig.ServiceConfig.NgvsaServiceUrl + "/v1/cloud_live/speciallive/startPull2Live"
	Url, err := url.Parse(urlString)
	if err != nil {
		return "", err
	}
	params.Set("tenant_id", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	e.Log.Trace("NgvsaServiceUrl:", urlPath)

	// 参数
	data := make(map[string]interface{})
	data["type"] = d.Type
	data["source"] = d.Source
	data["pushUrl"] = d.PushUrl
	// Marshal
	e.Log.Trace(data)
	bytesData, _ := json.Marshal(data)
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return "", err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return "", err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return "", err
	}
	e.Log.Trace(string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").String() != "200" {
		return "", errors.New(result.Get("message").String())
	}
	return result.Get("data").String(), nil
}

func (e *CloudLive) StopPullLive(d dto.StopPullLiveReq) error {
	params := url.Values{}
	urlString := ext.ExtConfig.ServiceConfig.NgvsaServiceUrl + "/v1/cloud_live/speciallive/stopPull2Live"
	Url, err := url.Parse(urlString)
	if err != nil {
		return err
	}
	params.Set("tenant_id", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	e.Log.Trace("NgvsaServiceUrl:", urlPath)

	// 参数
	data := make(map[string]interface{})
	data["id"] = d.Id
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(data)
	// 获取 request请求
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace(string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").String() != "200" && result.Get("code").String() != "404" {
		return errors.New(result.Get("message").String())
	}
	return nil
}

func (e *CloudLive) StartPushLive(d dto.StartPushLiveReq) error {

	params := url.Values{}
	urlString := ext.ExtConfig.ServiceConfig.NgvsaServiceUrl + "/v1/cloud_live/"
	//拼接请求地址
	urlString = urlString + d.LiveId + "/resume"
	Url, err := url.Parse(urlString)
	if err != nil {
		return err
	}
	params.Set("tenant_id", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	e.Log.Trace("StartPushLive:", urlPath)

	// 参数
	data := make(map[string]interface{})
	data["id"] = d.Id
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(data)
	// 获取 request请求
	request, err := http.NewRequest("PUT", urlPath, bytes.NewReader(bytesData))
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("StartPushLive", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").String() != "200" && result.Get("code").String() != "404" {
		return errors.New(result.Get("message").String())
	}
	return nil
}

func (e *CloudLive) StopPushLive(d dto.StopPushLiveReq) error {

	params := url.Values{}
	urlString := ext.ExtConfig.ServiceConfig.NgvsaServiceUrl + "/v1/cloud_live/"
	//拼接请求地址
	urlString = urlString + d.LiveId + "/forbid"
	Url, err := url.Parse(urlString)
	if err != nil {
		return err
	}
	params.Set("tenant_id", d.TenantId)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	e.Log.Trace("StopPushLive:", urlPath)

	// 参数
	data := make(map[string]interface{})
	data["id"] = d.Id
	bytesData, _ := json.Marshal(data)
	e.Log.Trace(data)
	// 获取 request请求
	request, err := http.NewRequest("PUT", urlPath, bytes.NewReader(bytesData))
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}

	request.Header.Add("Content-Type", "application/json")
	if err != nil {
		e.Log.Errorf("GetHttpSkip Request Error:", err)
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		e.Log.Errorf("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Trace("StopPushLive", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").String() != "200" && result.Get("code").String() != "404" {
		return errors.New(result.Get("message").String())
	}
	return nil
}
